package pos.control;

import java.util.ArrayList;
import pos.entity.PriceAdjustment;
import pos.entity.PriceAdjustment.PriceAdjustmentType;
import pos.entity.PurchasedItem;

/**
 *
 * @author Justin Hume
 */
public class PurchasedItemControl {

    //This method CALCULATES tax for each purchased item in the current list
    public ArrayList<PurchasedItem> updatePurchasedItemPriceAttributes(ArrayList<PurchasedItem> purchasedItemList) {

        //For each purchased item
        for (PurchasedItem item : purchasedItemList) {

            //sum the price adjustments EXCLUDING tax adjustments
            double sumNonTaxAdjustments = 0;

            for (PriceAdjustment adj : item.getPriceAdjustments()) {

                //If NOT a tax type
                if (!(adj.getPriceAdjustmentType() == PriceAdjustmentType._TAX_)) {

                    sumNonTaxAdjustments += adj.getPriceAdjustmentAmount();
                }
            }

            //Update total price on purchased item
            double totalPrice = item.getBasePrice() - sumNonTaxAdjustments;
            item.setTotalPrice(totalPrice);

            //Add tax adjustments
            TaxControl taxControl = new TaxControl();
            taxControl.addPurchasedItemTax(item);
        }

        //Ensure that all price attribute fields are recalculated
        purchasedItemList = calculateTotalPriceForPurchasedItems(purchasedItemList);

        return purchasedItemList;
    }

    //Calculate current total price for each purchased item
    private ArrayList<PurchasedItem> calculateTotalPriceForPurchasedItems(ArrayList<PurchasedItem> purchasedItemList) {

        //For each purchased item
        for (PurchasedItem item : purchasedItemList) {

            //Ensure total price is calculated
            double sumNonTaxAdjustments = 0;
            double sumTaxAdjustments = 0;

            for (PriceAdjustment adj : item.getPriceAdjustments()) {

                //If NOT a tax type
                if (!(adj.getPriceAdjustmentType() == PriceAdjustmentType._TAX_)) {

                    sumNonTaxAdjustments += adj.getPriceAdjustmentAmount();
                }
                //IS a tax type
                else {

                    sumTaxAdjustments += adj.getPriceAdjustmentAmount();
                }
            }

            //Update total price on purchased item
            double totalPrice = item.getBasePrice() - sumNonTaxAdjustments + sumTaxAdjustments;

            //Set price attribute fields on the purchased item
            item.setTotalPrice(totalPrice);
            item.setTaxes(sumTaxAdjustments);
            item.setPriceAdjustedAmount(sumNonTaxAdjustments);
        }

        return purchasedItemList;
    }    
}
